import axios, {
  AxiosRequestHeaders,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { useSystemStore } from "../store/login";
import { layer } from "@layui/layui-vue";
import router from "../router";

type TAxiosOption = {
  timeout: number;
  baseURL: string;
};

const config: TAxiosOption = {
  timeout: 15000,
  baseURL: "/",
};

const handleLoginTimeOut = () => {
  layer.msg("登录超时，请重新登录", { icon: 2, time: 1000 });
  const userInfoStore = useSystemStore();
  userInfoStore.removeLoginInfo();
  router.push("/login");
};

class Http {
  service;
  constructor(config: TAxiosOption) {
    this.service = axios.create(config);

    /* 请求拦截 */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const userInfoStore = useSystemStore();
        if (userInfoStore.token) {
          (config.headers as AxiosRequestHeaders).token =
            userInfoStore.token as string;
        } else {
          if (router.currentRoute.value.path !== "/login") {
            router.push("/login");
          }
          const token =
            "yJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1Y28iOiJhZG1pbjEiLCJhdWQiOiI2ODgxNjQwNzA2ODcyNDgzODQiLCJ1bmEiOiJhZG1pbjEiLCJ1b3IiOiIxIiwiZXhwIjoxNzEwNzA3NTMwfQ.PNW0bJAgtBjiGCQG-av-bPv0KE3XUSPlIuK89cx_6-A";
          config.headers.token = token;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      },
    );

    /* 响应拦截 */
    this.service.interceptors.response.use(
      (response: AxiosResponse<any>) => {
        switch (response.status) {
          case 200:
            return response.data;
          case 504:
            return handleLoginTimeOut();
          // return response.data;
          default:
            break;
        }
      },
      (error) => {
        if (error.response?.status === 401) {
          return handleLoginTimeOut();
        }

        return Promise.reject(error);
      },
    );
  }

  /* GET 方法 */
  get<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.get(url, { params, ..._object });
  }
  /* POST 方法 */
  post<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.post(url, params, _object);
  }
  /* PUT 方法 */
  put<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.put(url, params, _object);
  }
  /* DELETE 方法 */
  delete<T>(url: string, params?: any, _object = {}): Promise<any> {
    return this.service.delete(url, { params, ..._object });
  }
}

export default new Http(config);
